package com.bpmn.flow.controller;

import com.bpmn.common.annotation.ResponseInfoWrapper;
import com.bpmn.common.entity.ResponseResult;
import com.bpmn.flow.dto.ProcessStartDTO;
import com.bpmn.flow.service.ProcessStartService;
import com.bpmn.flow.service.TaskOperationService;
import com.bpmn.utils.FlowableUtils;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author rain
 */
@RestController
@ResponseInfoWrapper
@RequiredArgsConstructor
@RequestMapping("/workflow/process")
@Tag(name = "流程申请")
@Validated
@Slf4j
public class ProcessStartController {

    private final ProcessStartService processStartService;

    private final TaskOperationService taskOperationService;

    @Operation(summary = "发起流程申请")
    @PostMapping("/start")
    public ResponseResult<String> startProcess(@Validated @RequestBody ProcessStartDTO dto) {
        String processInstanceId = FlowableUtils.executeAuthenticatedUserId(
                dto.getUserId(),
                () -> {
                    String processId = processStartService.startProcess(dto);
                    taskOperationService.autoCompleteFirstTask(processId);
                    return processId;
                });
        return ResponseResult.successStr(processInstanceId);
    }

}